package com.ebeitech.auction.view.homepage;

import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

import com.ebeitech.auction.R;
import com.ebeitech.auction.application.EbeiApplication;
import com.ebeitech.auction.constants.ActionConstants;
import com.ebeitech.auction.constants.CommonConstants;
import com.ebeitech.auction.push.xiaomi.PushUtils;
import com.ebeitech.auction.qqim.util.QQIMUtil;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.util.Log;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.view.StatusBarCompat;

import java.util.List;

/**
 * Created by alice on 2017/10/24.
 */
public class BaseActivity extends FragmentActivity {

	private boolean isForeground;
	private boolean isOnPause;
	private KeyguardManager mKeyguardManager;

	private Context mContext;

	private String mUserAccount;

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.Activity#startActivity(android.content.Intent)
	 */
	@Override
	public void startActivity(Intent intent) {
		// TODO Auto-generated method stub
		super.startActivity(intent);
		overridePendingTransition(R.anim.ebei_in_from_right, R.anim.ebei_out_to_left);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.Activity#startActivityForResult(android.content.Intent,
	 * int, android.os.Bundle)
	 */
	@Override
	public void startActivityForResult(Intent intent, int requestCode,
									   Bundle options) {
		// TODO Auto-generated method stub
		super.startActivityForResult(intent, requestCode, options);
		overridePendingTransition(R.anim.ebei_in_from_right, R.anim.ebei_out_to_left);
	}

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		EbeiApplication.addActivity(this);
		StatusBarCompat.compat(this);
		mContext = this;
		mUserAccount = SPManager.getInstance().get(SPConstants.USER_ACCOUNT, "");
		mKeyguardManager = (KeyguardManager) mContext.getSystemService(mContext.KEYGUARD_SERVICE);
		registerBroadCast();
	}

	@Override
	protected void onStart() {
		super.onStart();
		StatusBarCompat.fitsSystemWindows(this);
	}

	/*
		 * (non-Javadoc)
		 *
		 * @see android.app.Activity#finish()
		 */
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		overridePendingTransition(R.anim.ebei_in_from_left, R.anim.ebei_out_to_right);
	}

	private void registerBroadCast() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(ActionConstants.ACTION_EXIT_APP);
		registerReceiver(mBroadcastReceiver, myIntentFilter);
	}

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (ActionConstants.ACTION_EXIT_APP.equals(action)) {
				finish();
			}
		}
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		EbeiApplication.removeActivity(this);
		unregisterReceiver(mBroadcastReceiver);
		int count = SPManager.getInstance().get("dialogCount", 0);
		if (count > 0) {
			sendBroadcast(new Intent("ACTION_EXIT_DIALOG"));
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isOnPause = false;
		isForeground = SPManager.getInstance().get("isForeground", true);
		if (!isForeground) {
			Log.i("APP重新进入前台");
			boolean isLoginOffline = SPManager.getInstance().get(CommonConstants.IS_LOGIN_OFFLINE, true);
			if (CommonConstants.IS_MESSAGE_OPEN && !isLoginOffline) {
				Log.i("QQIM正在登陆");
				QQIMUtil.getInstance().doLogin(mContext, mUserAccount);
			}

			/*QPIApplication app = (EbeiApplication) getApplication();
			if (app != null) {
				Log.i("app.startLocate()");
				app.addOnLocationClientLocatedListener(this);
				app.startLocate();
			}*/

			// 检查更新
			//checkVersionAuto();
		}
		isForeground = true;
		SPManager.getInstance().put("isForeground", true);
		SPManager.getInstance().put(CommonConstants.IS_APP_FOREGROUND, true);

		Log.i("不在接收第三方推送");
		PushUtils.stopPushService(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		isOnPause = true;
	}

	/*
		 * (non-Javadoc)
		 *
		 * @see android.app.Activity#onStop()
		 */
	@Override
	protected void onStop() {
		super.onStop();
		if (!isAppOnForeground()) {
			Log.i("APP进入后台");
			isForeground = false;
			SPManager.getInstance().put("isForeground", isForeground);
			SPManager.getInstance().put(CommonConstants.IS_APP_FOREGROUND, false);

			Log.i("启动第三方推送");
			PushUtils.startPushService(this);
		} else {
			SPManager.getInstance().put(CommonConstants.IS_APP_FOREGROUND, true);
		}

		/*QPIApplication app = (QPIApplication) getApplication();
		if (app != null) {
			app.removeOnLocationClientLocatedListener(this);
		}*/
	}

	/**
	 * 程序是否在前台运行
	 *
	 * @return
	 */
	public boolean isAppOnForeground() {
		if (mKeyguardManager.inKeyguardRestrictedInputMode()){
			return  false;
		}

		ActivityManager activityManager = (ActivityManager) getApplicationContext()
				.getSystemService(Context.ACTIVITY_SERVICE);
		String packageName = getApplicationContext().getPackageName();
		/**
		 * 获取Android设备中所有正在运行的App
		 */
		List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		if (appProcesses == null)
			return false;

		for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
			// The name of the process that this object is associated with.
			if (appProcess.processName.equals(packageName)
					&& appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				return true;
			}
		}

		return false;
	}

	public boolean isOnPause() {
		return isOnPause;
	}

	public void exit() {

	}

	/*public void checkVersionAuto() {
		if (!PublicFunctions.isNetworkAvailable(mContext)) {
			return;
		}
		// 一天只检查一次
		String checkUpdateTime = QPIApplication.getString("checkUpdateTime", "");
		boolean isNeedCheckUpdate = false;
		String currentTime = PublicFunctions.getCurrentTime();
		if (PublicFunctions.isStringNullOrEmpty(checkUpdateTime)) {
			isNeedCheckUpdate = true;
		} else if (checkUpdateTime.length() > 9 && currentTime.substring(0, 10).compareTo(checkUpdateTime.substring(0, 10)) > 0) {
			isNeedCheckUpdate = true;
		}
		if (!isNeedCheckUpdate) {
			return;
		}
		checkUpdateTime = currentTime;
		QPIApplication.putString("checkUpdateTime", checkUpdateTime);

		new AsyncTask<Void, Void, Void>() {

			private String _result;
			private Bundle _bundle;

			@Override
			protected Void doInBackground(Void... params) {
				// TODO Auto-generated method stub
				String urlGet = PropertyNoticeApi.CHECK_VERSION_MANUALLY;
				ParseTool parseTool = new ParseTool();
				try {
					_result = parseTool.getUrlDataOfGet(urlGet, false);
				} catch (Exception e) {
					e.printStackTrace();
					_result = null;
				}
				if (_result != null) {
					_bundle = parseTool.getAndroidVersionAndApkUrl(_result);
				}
				return null;
			}

			protected void onPostExecute(Void result) {
				int currentVersion = PublicFunction.getCurrentVersion(mContext);
				int localRecordServiceVersion = PublicFunction.getPrefInt(mContext, PropertyNoticeConstants.SYSTEM_VERSION_ON_SERVICE, currentVersion);
				if (_result != null) {
					int version = _bundle.getInt("version");
					final String url = _bundle.getString("androidUrl");
					Log.i("","服务器版本：" + version);
					Log.i("","本地版本：" + currentVersion);
					PublicFunction.setPrefInt(mContext,PropertyNoticeConstants.SYSTEM_VERSION_ON_SERVICE,version);
					if (version > currentVersion) {
						new VersionCheckDialog(mContext, url).show();
					}
				}else{
					Log.i("","本地记录版本：" + localRecordServiceVersion);
					Log.i("","本地版本：" + currentVersion);
					if((localRecordServiceVersion > currentVersion)	&&
							PublicFunctions.fileIsExists(QPIConstants.FILE_DOWNLOAD_DIR,QPIConstants.DOWNLOAD_APK_NAME)){
							//网络连接失败，但检测到本地有最新未安装的版本
						String apkPath = QPIConstants.FILE_DOWNLOAD_DIR + QPIConstants.DOWNLOAD_APK_NAME;
						PublicFunctions.doOpenFile(apkPath, mContext);
						PublicFunctions.sendCheckVersionBroadcast(mContext,4,0);
					}
				}
			};

		}.executeOnExecutor(QPIThreadPool.HTTP_THREAD_POOL);
	}*/

}
